//
//  UnFinishedOrderViewController.m
//  FMJY
//
//  Created by 艾玩科技 on 17/4/10.
//  Copyright © 2017年 随心. All rights reserved.
//

#import "UnFinishedOrderViewController.h"
#import "ReceivedorderTableViewCell.h"
#import "UnFinishedOrderDetailViewController.h"
#import "SRRefreshView.h"
#import <MJRefresh/MJRefresh.h>


@interface UnFinishedOrderViewController ()<UITableViewDelegate,UITableViewDataSource,AVAudioPlayerDelegate,playAlertMusicDelegate>
{
    NSMutableArray *no_AcceptDataArr;//获取到的未接单列表
    UIButton *footBtn;
    
    //播放音频的控件
    AVAudioPlayer *_audioPlayer;
    AVPlayer *_avPlayer;
    //总数和总页数
    NSInteger totalCount;
    NSInteger totalPage;
    
    NSInteger page;
    NSInteger pagesize;
}

@property (nonatomic,strong) UITableView *unfinishedOrderV;
@property (nonatomic,strong) UIButton *noDataV;
@end

@implementation UnFinishedOrderViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"未完成订单";
    page = 1;
    pagesize = 10;
    no_AcceptDataArr = [[NSMutableArray alloc] init];
    _unfinishedOrderV = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, KScreenHeight)];
    _unfinishedOrderV.separatorStyle = UITableViewCellSeparatorStyleNone;
    _unfinishedOrderV.delegate = self;
    _unfinishedOrderV.dataSource =self;
    _unfinishedOrderV.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNo_AcceptDataArr)];
    _unfinishedOrderV.mj_footer = [MJRefreshBackFooter footerWithRefreshingTarget:self refreshingAction:@selector(requsetMoreData)];
    [_unfinishedOrderV.mj_header beginRefreshing];
    [self.view addSubview:_unfinishedOrderV];
    
    //加载服务商未分配订单数据
    //    [self loadNo_AcceptDataArr];
    [self noDataView];
}

-(void)noDataView{
    _noDataV = [UIButton buttonWithType:UIButtonTypeSystem];
    _noDataV.hidden = YES;
    _noDataV.frame =CGRectMake((KScreenWidth-KScreenWidth/2.5)/2, (KScreenHeight-40)/2, KScreenWidth/2.5, 40);
    [_noDataV setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    [_noDataV addTarget:self action:@selector(clickNoData) forControlEvents:UIControlEventTouchUpInside];
    [_noDataV setTitle:@"暂无数据点击加载" forState:UIControlStateNormal];
    [self.view addSubview:_noDataV];
}

-(void)clickNoData
{
    [_unfinishedOrderV.mj_header beginRefreshing];
}

-(void)loadNo_AcceptDataArr
{
#pragma mark -- 服务商未完成订单列表 --
    [CoreWork ServiceProviderUnFinishOrderListWithloginToken:GetUserLoginToken page:[NSNumber numberWithInteger:page] pageSize:[NSNumber numberWithInteger:pagesize]  Block:^(id responsObject) {
        
        
#pragma mark -- 服务器报错  --
        if (![responsObject isKindOfClass:[NSDictionary class]]) {
            
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"服务器开小差了，请稍后重试" preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction *sure = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
            
            [alert addAction:sure];
            [self presentViewController:alert animated:YES completion:nil];
            
            return ;
            
            
        }
        
#pragma mark -- 报错 --
        if (([responsObject isKindOfClass:[NSDictionary class]] ) && ([[responsObject objectForKey:@"status"] integerValue ] == 0) ) {
            
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:[NSString stringWithFormat:@"%@", [responsObject objectForKey:@"message"]] preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction *sure = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
            
            [alert addAction:sure];
            [self presentViewController:alert animated:YES completion:nil];
            
            return ;
        }
#pragma mark -- 账号在另一个地方登录，被迫退出 --
        else if (([responsObject isKindOfClass:[NSDictionary class]]) && ([[responsObject objectForKey:@"status"] integerValue] == -3))
        {
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:[NSString stringWithFormat:@"%@",[responsObject objectForKey:@"message"]] preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction *sure = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                
                //调用退出接口
                [CoreWork logOutWithloginToken:GetUserLoginToken Block:^(id responsObject) {
                    //                     [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"isLogin"];
                    [self.navigationController presentViewController:[[LogInViewController alloc] init] animated:YES completion:nil];
                }];
                
            }];
            
            [alert addAction:sure];
            [self presentViewController:alert animated:YES completion:nil];
            
            return ;
        }
        
        totalPage =[[[responsObject objectForKey:@"data"] objectForKey:@"totalPage"] integerValue];
        
        if (![[responsObject objectForKey:@"data"]isKindOfClass:[NSDictionary class]]) {
            return;
        }
        no_AcceptDataArr = [[responsObject objectForKey:@"data"] objectForKey:@"dataList"];
        
        no_AcceptDataArr.count==0?(_noDataV.hidden = NO):(_noDataV.hidden = YES);
        
        //判断是否有服务商未分配司机的单子，有的话播放提示音
        NSMutableArray *array2 = [NSMutableArray array];
        for (int i = 0; i <no_AcceptDataArr.count; i ++) {
            
            [array2 addObject:[no_AcceptDataArr[i] objectForKey:@"status"]];
            
            if ([array2[i] integerValue] == 2030) {
                
                [_audioPlayer play];
            }
        }
        
        
        [_unfinishedOrderV reloadData];
    }];
    
    [_unfinishedOrderV.mj_header endRefreshing];
}

-(void)requsetMoreData{
    if (page < totalPage +1)
    {
        page = page +1;
        [self loadNo_AcceptDataArr];
    }
#pragma mark -- 服务商未完成订单列表 --
    [CoreWork ServiceProviderUnFinishOrderListWithloginToken:GetUserLoginToken page:[NSNumber numberWithInteger:page] pageSize:[NSNumber numberWithInteger:pagesize]  Block:^(id responsObject) {
        
        
#pragma mark -- 服务器报错  --
        if (![responsObject isKindOfClass:[NSDictionary class]]) {
            
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"服务器开小差了，请稍后重试" preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction *sure = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
            
            [alert addAction:sure];
            [self presentViewController:alert animated:YES completion:nil];
            
            return ;
            
            
        }
        
#pragma mark -- 报错 --
        if (([responsObject isKindOfClass:[NSDictionary class]] ) && ([[responsObject objectForKey:@"status"] integerValue ] == 0) ) {
            
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:[NSString stringWithFormat:@"%@", [responsObject objectForKey:@"message"]] preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction *sure = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
            
            [alert addAction:sure];
            [self presentViewController:alert animated:YES completion:nil];
            
            return ;
        }
#pragma mark -- 账号在另一个地方登录，被迫退出 --
        else if (([responsObject isKindOfClass:[NSDictionary class]]) && ([[responsObject objectForKey:@"status"] integerValue] == -3))
        {
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:[NSString stringWithFormat:@"%@",[responsObject objectForKey:@"message"]] preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction *sure = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                
                //调用退出接口
                [CoreWork logOutWithloginToken:GetUserLoginToken Block:^(id responsObject) {
                    //                     [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"isLogin"];
                    [self.navigationController presentViewController:[[LogInViewController alloc] init] animated:YES completion:nil];
                }];
                
            }];
            
            [alert addAction:sure];
            [self presentViewController:alert animated:YES completion:nil];
            
            return ;
        }
        
        totalPage =[[[responsObject objectForKey:@"data"] objectForKey:@"totalPage"] integerValue];
        
        if (![[responsObject objectForKey:@"data"]isKindOfClass:[NSDictionary class]]) {
            return;
        }
//        no_AcceptDataArr
        NSArray *arr = [[responsObject objectForKey:@"data"] objectForKey:@"dataList"];
        if (arr.count>0) {
            [no_AcceptDataArr insertObjects:arr atIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(no_AcceptDataArr.count, arr.count)]];
        }
        
        no_AcceptDataArr.count==0?(_noDataV.hidden = NO):(_noDataV.hidden = YES);
        
        //判断是否有服务商未分配司机的单子，有的话播放提示音
        NSMutableArray *array2 = [NSMutableArray array];
        for (int i = 0; i <no_AcceptDataArr.count; i ++) {
            
            [array2 addObject:[no_AcceptDataArr[i] objectForKey:@"status"]];
            
            if ([array2[i] integerValue] == 2030) {
                
                [_audioPlayer play];
            }
        }
        
        
        [_unfinishedOrderV reloadData];
    }];

    [_unfinishedOrderV.mj_footer endRefreshing];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

#pragma mark 创建cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    // 已接订单的cell
    ReceivedorderTableViewCell *receivedOrderCell =[tableView dequeueReusableCellWithIdentifier:@"receiveorderCell"];
    
    if (!receivedOrderCell) {
        
        receivedOrderCell =[[[NSBundle mainBundle] loadNibNamed:@"ReceivedorderTableViewCell" owner:nil options:nil] lastObject];
        
        
    }
    if (no_AcceptDataArr.count > 0 &&([[no_AcceptDataArr[indexPath.row] objectForKey:@"status" ] integerValue ] ==2030 )) {
        
        receivedOrderCell.backgroundColor = [UIColor colorWithRed:1.000 green:0.000 blue:0.475 alpha:1.00];
        
        
    }
    
    //服务类型
    receivedOrderCell.seveiceTypeLabel.text= [NSString stringWithFormat:@"%@",[no_AcceptDataArr[indexPath.row] objectForKey:@"helpTypeText"]];
    //救援地点
    receivedOrderCell.seveiceAddressLabel.text= [NSString stringWithFormat:@"%@",[no_AcceptDataArr[indexPath.row] objectForKey:@"addr"]];
    //服务类型
    receivedOrderCell.passTimeLabel.text= [NSString stringWithFormat:@"状态：%@",[no_AcceptDataArr[indexPath.row] objectForKey:@"statusText"]];
    receivedOrderCell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;
    
    
    
    
    return receivedOrderCell;
    
    
}
//cell高度
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 77;
    
}
//cell个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return no_AcceptDataArr.count;
}
//cell点击方法
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    UnFinishedOrderDetailViewController *unfinishedOrderdetailVC = [[UnFinishedOrderDetailViewController alloc] init];
    unfinishedOrderdetailVC.undealDataDic = no_AcceptDataArr[indexPath.row];
    unfinishedOrderdetailVC.orderStatusNumStr = [NSString stringWithFormat:@"%@",[no_AcceptDataArr[indexPath.row] objectForKey:@"status"]];
    unfinishedOrderdetailVC.undealOrderNumStr = [NSString stringWithFormat:@"%@",[no_AcceptDataArr[indexPath.row] objectForKey:@"orderNo"]];
    
    unfinishedOrderdetailVC.PlayOrStopDelegateA = self;
    [self.navigationController pushViewController:unfinishedOrderdetailVC animated:YES];
    
}


-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    
    //AVAudioPlayer
    //查找本地音乐文件路径
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"newOrder" ofType:@"mp3"];
    
    //构建URL
    NSURL *url2 = [NSURL fileURLWithPath:filePath];
    
    //创建音乐播放器
    _audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url2 error:nil];
    
    //根据URL地址来读取音乐文件（写在ViewDidLoad中会自动播放）
    [_audioPlayer prepareToPlay];
    
    _audioPlayer.delegate = self;
    _audioPlayer.numberOfLoops = -1;//播放次数，设置为负数时无限循环播放，直至调用stop方法
}
#pragma mark -- 代理：接单时提示音关闭 --
-(void)playOrStop
{
    [_audioPlayer stop];
}




@end
